package com.ibeeking.found.cop.b.rest.service.impl;

import com.ibeeking.found.cop.b.rest.service.ICopJobCreateService;
import com.ibeeking.found.common.constants.JobExecutorHandlerConstant;

import com.ibeeking.found.cop.service.common.param.CopJobHandleParam;
import com.ibeeking.gmc.job.core.enums.ExecutorBlockStrategyEnum;
import com.ibeeking.gmc.job.core.enums.RouteStrategyEnum;
import com.ibeeking.gmc.job.core.glue.GlueTypeEnum;

import com.ibeeking.found.job.model.JobInfoModel;
import com.ibeeking.found.job.service.IJobService;

import com.ibeeking.nematos.constants.enums.LogClassifyEnum;
import com.ibeeking.nematos.exception.BusinessException;
import com.ibeeking.nematos.log.utils.LogUtils;
import com.ibeeking.nematos.utils.cron.CronUtil;
import com.ibeeking.nematos.utils.cron.TaskScheduleModel;

import com.ibeeking.nematos.utils.json.JsonUtils;
import com.ibeeking.nematos.utils.result.ResponseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.concurrent.Future;

/**
 * @ClassName CopJobCreateServiceImpl
 * @Description
 * @Author ibeeking
 * @Date 2021-02-05 10:13
 **/
@Service
public class CopJobCreateServiceImpl  implements ICopJobCreateService {

    private static final Logger log = LoggerFactory.getLogger(CopJobCreateServiceImpl.class);

    @Resource
    private IJobService jobServiceImpl;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean createJobInfoForSendMassMessage(Integer tenantId, TaskScheduleModel scheduleModel, CopJobHandleParam handleParam){
        //构建任务体
        LogUtils.info("====================创建客户发送消息任务......=====================");
        JobInfoModel model = new JobInfoModel();
        model.setBusinessKey(String.valueOf(tenantId));
        model.setJobName(tenantId + "_客户群发消息定时任务");
        model.setType(1);

        model.setJobCron(CronUtil.createCronExpression(scheduleModel));
        model.setJobDesc("客户群发消息定时任务");
        model.setAuthor("系统创建");
        model.setRouteStrategyEnum(RouteStrategyEnum.ROUND);
        model.setExecutorHandler(JobExecutorHandlerConstant.TENANT_COP_SEND_MASS_MESSAGE_TO_WXCP);
        model.setExecutorParam(JsonUtils.toJsonStr(handleParam));
        model.setExecutorBlockStrategyEnum(ExecutorBlockStrategyEnum.SERIAL_EXECUTION);
        model.setExecutorTimeout(4);
        model.setExecutorFailRetryCount(2);
        model.setGlueTypeEnum(GlueTypeEnum.BEAN);
        model.setTriggerStatus(1);
        //开始创建/修改任务
        Future<ResponseResult<Boolean>> job = jobServiceImpl.modifyJob(model);
        //获取任务创建/修改结果
        if (job.isDone()) {
            try {
                ResponseResult<Boolean> responseResult = job.get();
                LogUtils.info("====================客户群发消息任务....完成=====================");
                if (!responseResult.getData()) {
                    LogUtils.error(LogClassifyEnum.ERROR_LOG, "定时任务删除失败[{}]", responseResult.getMsg());
                    throw new BusinessException("定时任务删除失败");
                }
            } catch (Exception e) {
                LogUtils.error("{}_客户群发消息定时任务创建失败", tenantId, e);
                return false;
            }
        }
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean createJobInfoForSendGroupMassMessage(Integer tenantId, TaskScheduleModel scheduleModel, CopJobHandleParam handleParam) {
        //构建任务体
        LogUtils.info("====================创建客户群发送消息任务......=====================");
        JobInfoModel model = new JobInfoModel();
        model.setBusinessKey(String.valueOf(tenantId));
        model.setJobName(tenantId + "_客户群群发消息定时任务");
        model.setType(2);

        model.setJobCron(CronUtil.createCronExpression(scheduleModel));
        model.setJobDesc("客户群群发消息定时任务");
        model.setAuthor("系统创建");
        model.setRouteStrategyEnum(RouteStrategyEnum.ROUND);
        model.setExecutorHandler(JobExecutorHandlerConstant.TENANT_COP_SEND_GROUP_MASS_MESSAGE_TO_WXCP);
        model.setExecutorParam(JsonUtils.toJsonStr(handleParam));
        model.setExecutorBlockStrategyEnum(ExecutorBlockStrategyEnum.SERIAL_EXECUTION);
        model.setExecutorTimeout(4);
        model.setExecutorFailRetryCount(2);
        model.setGlueTypeEnum(GlueTypeEnum.BEAN);
        model.setTriggerStatus(1);
        //开始创建/修改任务
        Future<ResponseResult<Boolean>> job = jobServiceImpl.modifyJob(model);
        //获取任务创建/修改结果
        if (job.isDone()) {
            try {
                ResponseResult<Boolean> responseResult = job.get();
                LogUtils.info("====================客户群群发消息任务....完成=====================");
                if (!responseResult.getData()) {
                    LogUtils.error(LogClassifyEnum.ERROR_LOG, "定时任务删除失败[{}]", responseResult.getMsg());
                    throw new BusinessException("定时任务删除失败");
                }
            } catch (Exception e) {
                LogUtils.error("{}_客户群发消息定时任务创建失败", tenantId, e);
                return false;
            }
        }
        return true;
    }
}
